package org.devocean.groupbuying.service.impl;

import java.util.List;

import org.devocean.groupbuying.dao.PlanDAO;
import org.devocean.groupbuying.domain.ArticlesLocalization;
import org.devocean.groupbuying.domain.Plan;
import org.devocean.groupbuying.domain.Promotion;
import org.devocean.groupbuying.service.ArticlesService;
import org.devocean.groupbuying.service.ExploredService;
import org.devocean.groupbuying.service.PlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class PlanServiceImpl implements PlanService {

	@Autowired
	private PlanDAO planDAO;

	@Autowired
	private ArticlesService articlesService;

	@Autowired
	private ExploredService exploredService;

	@Transactional
	public Plan getPlanById(Integer id) {

		return planDAO.findPlanById(id);
	}

	@Transactional
	public Plan addOrUpdatePlan(Plan plan) {

		final Plan newplan;

		if (plan.getPlanID() == null) {
			newplan = planDAO.savePlan(plan);
		} else {
			for (Promotion pr : plan.getPromotions()) {
				exploredService.addOrUpdateExplored(pr);
			}
			newplan = planDAO.updatePlan(plan);
		}

		return newplan;
	}

	@Transactional
	public long countPlans() {
		return planDAO.countPlans();
	}

	@Transactional
	public List<Plan> getAllPlans() {

		return planDAO.findAllPlans();
	}

	@Transactional
	public List<Plan> getPlansbyProduct(Integer productID, String lang) {

		return planDAO.findPlansByProduct(productID, lang);
	}

	@Transactional
	public List<Plan> getAllPlans(String lang) {
		return planDAO.findAllPlans(lang);
	}

	public Plan getPlanByArticle(Integer articleID) {

		return planDAO.findPlanByArticle(articleID);
	}

	@Transactional
	public Plan getPlanByLang(Integer localizationKey,
			String localizationRequest) {

		Plan plan = planDAO
				.findPlanByLang(localizationKey, localizationRequest);
		if (plan != null) {
			return plan;
		} else {
			Plan newPlan = planDAO
					.findPlanByArticleLocalization(localizationKey);
			newPlan.getArticlesLocalization().setArticles(null);
			return newPlan;
		}
	}

	@Transactional
	public void deletePlan(Integer id) {
		ArticlesLocalization al = articlesService.getArticleById(id)
				.getArticlesLocalization();
		if (al.getArticles().size() > 1) {
			articlesService.removeArticle(id);
		} else {
			Plan plan = this.getPlanByArticleLocalization(al
					.getArticlesLocalizationID());
			planDAO.removePlan(plan.getPlanID());
		}

	}

	@Transactional
	private Plan getPlanByArticleLocalization(Integer al) {

		return planDAO.findPlanByArticleLocalization(al);
	}

}
